#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>

using namespace std;

typedef void(*work_t)(int);//函数指针类型
typedef void(*task_t)(int, pid_t);

void task1(int fd, pid_t pid)
{
    cout << "fd: " << fd << " pid: " << pid << ", 任务1" << endl;
}
void task2(int fd, pid_t pid)
{
    cout << "fd: " << fd << " pid: " << pid << ", 任务2" << endl;
}
void task3(int fd, pid_t pid)
{
    cout << "fd: " << fd << " pid: " << pid << ", 任务3" << endl;
}
task_t tasks[3] = {task1, task2, task3};

uint32_t NextTask() 
{
    return rand() % 3;//生成随机数
}

//有了重定向，只需到标准输入即可
void worker(int fd)
{
    while(true)
    {   
        uint32_t command_code = 0;//随机任务下标
        ssize_t n = read(0, &command_code, sizeof(command_code));
        if(n == sizeof(command_code))
        {
            if(command_code >= 3) continue;
            tasks[command_code](fd, getpid());
        }
        else if(n == 0)
        {
            cout << "sub process: " << getpid() << " quit..." <<endl;
            break;
        }
     }
}